#include "music.h"
#include "ui_music.h"
#include <QtNetwork/QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonObject>
#include <QJsonArray>
music::music(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::music)
{
    ui->setupUi(this);

    pModel = new QStandardItemModel(10,5,ui->tableView);
    //设置数据模型的表头
    QStringList list = QStringList()<<"歌名"<<"歌手"<<"专辑"<<"时长"<<"收藏";
    pModel->setHorizontalHeaderLabels(list);//设置数据的表头
    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
    playlist = new QMediaPlaylist;//媒体播放列表

    player = new QMediaPlayer;//媒体播放器
    player->setPlaylist(playlist);//把播放列表设置给播放器

    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
    connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(durationChangedSlot(qint64)));

    database =new mysql;
    query=QSqlQuery(database->database);

    QPixmap pixmap_list("D:/qtname/QT/QTchar/pic/list.png"); // 替换为实际图片路径
    ui->pushButton_3->setIcon(QIcon(pixmap_list));
    ui->pushButton_3->setIconSize(pixmap_list.size()); // 调整label大小以适应图片

    QPixmap pixmap_next("D:/qtname/QT/QTchar/pic/next.png"); // 替换为实际图片路径
    ui->pushButton_5->setIcon(QIcon(pixmap_next));
    ui->pushButton_5->setIconSize(pixmap_next.size()); // 调整label大小以适应图片

    QPixmap pixmap_start("D:/qtname/QT/QTchar/pic/suspend.png"); // 替换为实际图片路径
    ui->pushButton_4->setIcon(QIcon(pixmap_start));
    ui->pushButton_4->setIconSize(pixmap_start.size()); // 调整label大小以适应图片

    //    QPixmap pixmap_suspend("D:/qtname/QT/QTchar/pic/list.png"); // 替换为实际图片路径
    //    ui->label_3->setPixmap(pixmap_list);
    //    ui->label_3->resize(pixmap_list.size()); // 调整label大小以适应图片

}

void music::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    QPixmap pixmap("D:/qtname/QT/QTchar/pic/3.png");
    painter.drawPixmap(this->rect(),pixmap);

}

void music::on_pushButton_clicked()//查询歌曲按钮
{
    coll=1;
    QString str1=ui->lineEdit->text();
    //  qDebug()<<"11111111111111111111"<<endl;
    manager->get(QNetworkRequest(QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%0&type=1&offset=0&total=true&limit=10").arg(str1))));
}


void music::replyFinished(QNetworkReply * reply)//判断链接是否被解析
{
    // qDebug()<<"hello"<<endl;
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
    {
        qDebug()<<"访问服务器成功"<<endl;
        parseJson(reply->readAll());
    }
    else
    {
        qDebug()<<"匹配失败"<<endl;
    }

}


void music::on_tableView_doubleClicked(const QModelIndex &index)//点击列表
{
    if(index.column()==4)//判断按下的是否是收藏
    {
        pItem = pModel->item(index.row(),0);
        QString song_name=pItem->text();
        pItem = pModel->item(index.row(),1);
        QString songs=pItem->text();
        pItem = pModel->item(index.row(),2);
        QString collection=pItem->text();
        pItem = pModel->item(index.row(),3);
        QString song_time=pItem->text();
        //      qDebug()<<" "<<song_name<<" "<<songs<<" "<<collection<<" "<<song_time<<endl;
        QString str;
        if(coll==1)
        {
            str=QString("SELECT * FROM music_vip WHERE musicID=%1;").arg(musicID[index.row()]);
        }
        else
        {
            str=QString("SELECT * FROM music_vip WHERE musicID=%1;").arg(musicID_coll[index.row()]);
        }
        sql_test(str);
        QStandardItem* item = new QStandardItem();
        if(query.next())
        {
            if(coll==1)
            {
                str=QString("DELETE FROM music_vip WHERE musicID=%1;").arg(musicID[index.row()]);
            }
            else
            {
                str=QString("DELETE FROM music_vip WHERE musicID=%1;").arg(musicID_coll[index.row()]);
            }
            sql_test(str);
            QPixmap pixmap_2("D:/qtname/QT/QTchar/pic/1.png");
            item->setData(pixmap_2, Qt::DecorationRole);
            pModel->setItem(index.row(),index.column(),item);
        }
        else
        {
            if(coll==1)
            {
                str=QString("INSERT INTO music_vip VALUES ('%0','%1','%2','%3','%4');").arg(musicID[index.row()]).arg(song_name).arg(songs).arg(collection).arg(song_time);
            }
            else
            {
                str=QString("INSERT INTO music_vip VALUES ('%0','%1','%2','%3','%4');").arg(musicID_coll[index.row()]).arg(song_name).arg(songs).arg(collection).arg(song_time);
            }
            sql_test(str);
            QPixmap pixmap_1("D:/qtname/QT/QTchar/pic/2.png");
            item->setData(pixmap_1, Qt::DecorationRole);
            pModel->setItem(index.row(),index.column(),item);
        }
    }
    else
    {
        //qDebug()<<index.row()<<endl;
        playlist->setCurrentIndex(index.row());
        prev_next=index.row();
        player->play();
    }

}


void music::parseJson(QByteArray byteArray)//解析json音乐
{
    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    QString song_name;  //歌名
    QString singer;      //歌手
    QString collection;   //专辑
    QString song_time;     //时长
    unsigned int id;              //id号
    if(doc.isObject())
    {
        qDebug()<<"该文档是一个对象"<<endl;
        QJsonObject obj1 = doc.object();
        if(obj1.contains("result") == false)
        {
            qDebug()<<"错误的JSON对象"<<endl;
            return;
        }
        QJsonValue var = obj1.value("result");
        QJsonObject resultObj = var.toObject();
        if(resultObj.contains("songs") == false)
        {
            qDebug()<<"JSON对象没有歌曲"<<endl;
            return;
        }
        var = resultObj.value("songs");
        if(var.isArray())
        {
            QJsonArray songsArr = var.toArray();
            qDebug()<<"一共搜索到"<<songsArr.size()<<"首歌曲"<<endl;
            musicID.clear();
            playlist->clear();
            for(int i=0;i<songsArr.size();i++)
            {
                QJsonObject sonobj=songsArr[i].toObject();
                if(sonobj.contains("name"))//歌名
                {
                    QJsonValue varname=sonobj.value("name");
                    song_name=varname.toString();
                }
                if(sonobj.contains("id")) //id号
                {
                    QJsonValue varID=sonobj.value("id");
                    id=varID.toDouble();
                }
                if(sonobj.contains("album"))//专辑
                {
                    QJsonValue valbun=sonobj.value("album");
                    if(valbun.isObject())
                    {
                        QJsonObject albumObj = valbun.toObject();//把专辑的值转为对象
                        if(albumObj.contains("name"))
                        {
                            QJsonValue varAlbumName =  albumObj.value("name");
                            collection = varAlbumName.toString();//得到专辑名
                        }
                    }
                }
                if(sonobj.contains("artists"))//歌手
                {
                    QJsonValue varsongs=sonobj.value("artists");
                    if(varsongs.isArray())
                    {
                        QJsonArray song=varsongs.toArray();
                        for(int j=0;j<song.size();j++)
                        {
                            if(song[j].isObject())
                            {
                                QJsonObject artistsObj = song[j].toObject();
                                if(artistsObj.contains("name"))
                                {
                                    QJsonValue varArtistsName = artistsObj.value("name");
                                    singer+= varArtistsName.toString();//把名字加入到字符串中
                                    singer+=" ";//中间留一个空格
                                }

                            }
                        }
                    }
                }
                if(sonobj.contains("duration"))//时长
                {
                    QJsonValue vartime = sonobj.value("duration");
                    int var_time = vartime.toInt();
                    int min=var_time/1000/60;
                    int sec=var_time/100%60;
                    song_time=QString("%0:%1").arg(min).arg(sec);
                }
                musicID.push_back(id);
                qDebug()<<id<<endl;
                playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));
                qDebug()<<QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)<<endl;
                item = new QStandardItem(QString("%0").arg(song_name));
                qDebug()<<song_name<<endl;
                pModel->setItem(i,0,item);
                item = new QStandardItem(QString("%0").arg(singer));
                pModel->setItem(i,1,item);
                item = new QStandardItem(QString("%0").arg(collection));
                pModel->setItem(i,2,item);
                item = new QStandardItem(QString("%0").arg(song_time));
                pModel->setItem(i,3,item);
                QString str=QString("SELECT * FROM music_vip WHERE musicID=%1;").arg(id);
                sql_test(str);
                QStandardItem* item = new QStandardItem();
                if(query.next())
                {
                    QPixmap pixmap_2("D:/qtname/QT/QTchar/pic/2.png");
                    item->setData(pixmap_2, Qt::DecorationRole);
                    pModel->setItem(i,4,item);
                }
                else
                {
                    QPixmap pixmap_1("D:/qtname/QT/QTchar/pic/1.png");
                    item->setData(pixmap_1, Qt::DecorationRole);
                    pModel->setItem(i,4,item);
                }
            }
            ui->tableView->setModel(pModel);
            playlist->setCurrentIndex(0);
        }
    }
}

void music::positionChangedSlot(qint64 position)//根据歌曲时间来判断水平位置
{
    //  qDebug()<<position<<endl;
    ui->horizontalSlider->setValue(position);
}

void music::durationChangedSlot(qint64 duration)//绑定音乐时长和滑块
{
    qDebug()<<"当前歌曲的总时长为"<<duration<<"毫秒"<<endl;
    ui->horizontalSlider->setRange(0,duration);//设置滑块的总范围为歌曲的时长
}

void music::on_horizontalSlider_sliderReleased()//拖动进度滑块
{
    qint64 var = ui->horizontalSlider->value();//得到滑块当前值
    player->setPosition(var);//得到滑块当前值做为音乐播放的当前时间
}

music::~music()//析构函数
{
    delete ui;
}

void music::sql_test(QString str)//数据库函数
{
    if(!query.exec(str))
    {
        qDebug()<<query.lastError();
    }
    else
    {
        qDebug()<<"ok";

    }
}

void music::on_pushButton_2_clicked()//收藏按钮
{

    coll=2;
    QAbstractItemModel *model = ui->tableView->model(); // 获取模型
    QStandardItem* item_1;
    if (model) {
        model->removeRows(0, model->rowCount());
    }
    QString sql = "SELECT * FROM music_vip;";
    sql_test(sql);
    query.first();
    int i=0;
    playlist->clear();
    musicID_coll.clear();
    do {
        unsigned int id=query.value(0).toDouble();
        musicID_coll.push_back(id);
        QString music_name = query.value(1).toString();
        QString songs = query.value(2).toString();
        QString collection = query.value(3).toString();
        QString music_time =query.value(4).toString();
        item = new QStandardItem(QString("%0").arg(music_name));
        pModel->setItem(i,0,item);
        item = new QStandardItem(QString("%0").arg(songs));
        pModel->setItem(i,1,item);
        item = new QStandardItem(QString("%0").arg(collection));
        pModel->setItem(i,2,item);
        item = new QStandardItem(QString("%0").arg(music_time));
        pModel->setItem(i,3,item);
        item_1 = new QStandardItem();
        QPixmap pixmap("D:/qtname/QT/QTchar/pic/2.png");
        item_1->setData(pixmap, Qt::DecorationRole);
        pModel->setItem(i,4,item_1);
        i++;
        playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));

    } while (query.next()==true);

}


void music::on_pushButton_3_clicked()//上一首
{
    playlist->setCurrentIndex(--prev_next);
    player->play();
}

void music::on_pushButton_4_clicked()//暂停
{
    if (player->state() == QMediaPlayer::PlayingState) {
                player->pause(); // 暂停音乐
                QPixmap pixmap_start("D:/qtname/QT/QTchar/pic/start.png"); // 替换为实际图片路径
                ui->pushButton_4->setIcon(QIcon(pixmap_start));
                ui->pushButton_4->setIconSize(pixmap_start.size()); // 调整label大小以适应图片
            } else {
                player->play();  // 如果当前是暂停状态，则继续播放
                QPixmap pixmap_start("D:/qtname/QT/QTchar/pic/suspend.png"); // 替换为实际图片路径
                ui->pushButton_4->setIcon(QIcon(pixmap_start));
                ui->pushButton_4->setIconSize(pixmap_start.size()); // 调整label大小以适应图片
            }
}

void music::on_pushButton_5_clicked()//下一首
{
    playlist->setCurrentIndex(++prev_next);
    player->play();
}
